package com.zxd.interview.netty.towcommunication;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

/**
 * 封装为二进制数据
 */
public class PacketCodeC {

    private static final int MAGIC_NUMBER = 0x123456;

    public ByteBuf encode(Packet packet){
        // 构建 ByteBuf 对象
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.ioBuffer();;

        // 序列化Java
        byte[] bytes = Serializer.SERIALIZER_DEFAULT.serialize(byteBuf);

        // 实际编码
        // 注意编码的顺序7
        byteBuf.writeInt(MAGIC_NUMBER);
        byteBuf.writeByte(packet.getVersion());
        byteBuf.writeByte(Serializer.SERIALIZER_DEFAULT.getSerializerAlgorithm());
        byteBuf.writeByte(packet.getCommand());
        byteBuf.writeByte(bytes.length);
        byteBuf.writeBytes(bytes);

        return byteBuf;
    }



}
